﻿var thisBulider;
var thisBuliderName = "";
var fe_rep = {};
var YFID = 0;//产品研发ID
var containerList = {};
//按钮间的联动关系，若以后该关系改变需要另写json文件存档读档（改动的前提必然是增减母维度或设置权重）
var btnLinks = {
    departBtns: ["MktAvgIndex", "BdAvgIndex", "OpAvgIndex", "FinAvgIndex"],
    btns: ["DupontsFinancialSensitivity", "ProductsValidityAnalysis", "ProductionAndMarketingCooperationDetails", "OperationDetails", "StrategySelectionIdentification", "ChannelDevelopmentDetails", "MarketInputDetails", "Products4DControl", "ResourceUtilizationControl", "FinancialControl", "OverallOperatingSavings", "ScaleCostControl", "MktAvgIndex", "BdAvgIndex", "OpAvgIndex", "FinAvgIndex"],
    Links: {
        MktAvgIndex: ["MktAvgIndex", "ProductsValidityAnalysis", "ProductionAndMarketingCooperationDetails", "ChannelDevelopmentDetails", "MarketInputDetails", "Products4DControl", "ResourceUtilizationControl", "StrategySelectionIdentification"],
        BdAvgIndex: ["BdAvgIndex", "OperationDetails", "ChannelDevelopmentDetails"],
        OpAvgIndex: ["OpAvgIndex", "ProductionAndMarketingCooperationDetails", "OperationDetails", "OverallOperatingSavings"],
        FinAvgIndex: ["FinAvgIndex", "DupontsFinancialSensitivity", "FinancialControl", "ProductsValidityAnalysis", "MarketInputDetails", "OverallOperatingSavings", "ScaleCostControl"]
    }
};
//加载模块
function anaPart(anaPart, active = false, parent = thisBulider) {
    layui.use('layer', function () {
        var layer = layui.layer;
        var loading = layer.load();
        var anaContainer = $(`<div id="${anaPart}" class="whole-page"></div>`).css("visibility", "hidden");
        var rs;
        for (let i = 0; i < parent.length; i++) {
            if (parent[i].value.containerID == anaPart) {
                rs = [parent[i]];
                break;
            }
        }
        $("body").append(anaContainer);
        load(rs, anaContainer, active);
        specialCase(anaPart);
        PCflex();
        //返回按钮
        anaContainer.find(".body-inside").find(".section-header").find(".back").on("click", function () {
            pageToggle("out", anaContainer);
        });
        //页面进入
        pageToggle("in", anaContainer);
        layer.close(loading);
    })
}
//特殊情况特殊处理
function specialCase(anaPart) {
    switch (anaPart) {
        //公司分析主页-有联动按钮的初始化
        case "analysis-pro-comp":
            let partShow = "";//被展示的部门，若为""则全部展示
            var clickfun;
            for (let i = 0; i < btnLinks.departBtns.length; i++) {
                clickfun = (function (i) {
                    return function () {
                        if (partShow != btnLinks.departBtns[i]) {
                            for (let j = 0; j < btnLinks.btns.length; j++) {
                                $("#" + btnLinks.btns[j]).addClass("off");
                            }
                            for (let j = 0; j < btnLinks.Links[btnLinks.departBtns[i]].length; j++) {
                                $("#" + btnLinks.Links[btnLinks.departBtns[i]][j]).removeClass("off");
                            }
                            partShow = btnLinks.departBtns[i];
                        }
                        else {
                            for (let j = 0; j < btnLinks.btns.length; j++) {
                                $("#" + btnLinks.btns[j]).removeClass("off");
                            }
                            partShow = "";
                        }
                    }
                })(i);
                $("#" + btnLinks.departBtns[i]).on("click", clickfun);
            }
            break;
        //公司分析-产品有效性分析-平均产品生命周期中有一张根据产品数量的动态表格
        case "anaproductLifeSpan_3":
            //表格第0列和三行的初始化
            let tableCols = [[{ field: " ", title: " ", edit: "", key: "0-0", hide: false, type: "normal", width: 0 }]];
            let tableData = [{ " ": "开始日期", LAY_TABLE_INDEX: 0 }, { " ": "结束日期", LAY_TABLE_INDEX: 1 }, { " ": "总生存", LAY_TABLE_INDEX: 2 }];
            for (let i = 0; i < fe_rep._fe_rep_product.length; i++) {
                tableCols[0].push({
                    field: fe_rep._fe_rep_product[i].nv9,
                    title: fe_rep._fe_rep_product[i].nv9,
                    edit: "",
                    key: `0-${i + 1}`,
                    hide: false,
                    type: "normal",
                    width: 0
                });
                tableData[0][fe_rep._fe_rep_product[i].nv9] = numType(fe_rep._fe_rep_product[i].nv10, "date1");
                tableData[1][fe_rep._fe_rep_product[i].nv9] = numType(fe_rep._fe_rep_product[i].nv12, "date1");
                tableData[2][fe_rep._fe_rep_product[i].nv9] = numType(fe_rep._fe_rep_product[i].days, "int") + "天";
            }
            let tableDom = $("#productsSurviveTable");
            tableDom.append(`<table id="productsSurviveTableB" class="layui-hide" lay-filter="productsSurviveTableB"></table>`)
            setTable();
            function setTable() {
                layui.use('table', function () {
                    var table = layui.table;
                    //展示已知数据
                    table.render({
                        elem: '#productsSurviveTableB'
                        , cellMinWidth: 100
                        , cols: tableCols
                        , data: tableData
                        , even: true
                    });
                });
            }
            break;
        //零售商无上下游额外收入指标
        case "anaOperationDetails":
            if (fe_rep.fe_rep_cust.hy == '0003') $("#Negotiation").remove();
            break;
    }
}
//PC端flex排布
function PCflex() {
    if (window.innerWidth > window.innerHeight * 0.8) {
        var topLeftNow = 0;
        var topRightNow = 0;
        var count = $(".flex").children().length;
        for (var i = 0; i < count; i++) {
            $($(".flex").children()[i]).css({ "position": "absolute", "left": (i % 2) * 50 + "%" });
            if (i % 2 == 0) {
                $($(".flex").children()[i]).css("top", topLeftNow);
                topLeftNow += $($(".flex").children()[i]).height();
            }
            else if (i % 2 == 1) {
                $($(".flex").children()[i]).css("top", topRightNow);
                topRightNow += $($(".flex").children()[i]).height();
            }
        }
    }
}
//页面切换动画
function pageToggle(type, pageDom, callback) {
    var old_position = pageDom.css("position");
    if (type == "in") {
        pageDom
            .css({
                position: "absolute",
                left: "120vw",
                visibility: "visible"
            })
            .show()
            .animate({
                left: "0"
            }, 300, function () {
                pageDom.css("position", old_position);
                if (callback) callback();
            });
    }
    else if (type == "out") {
        pageDom
            .css({
                position: "absolute",
                left: "0vw"
            })
            .animate({
                left: "120vw"
            }, 300, function () {
                pageDom.css("position", old_position)
                    .hide()
                    .remove();
                if (callback) callback();
            });
    }
}
//加载方法
function load(rs, parent, active) {
    var type = "";
    var chartList = [];
    for (let i = 0; i < rs.length; i++) {
        type = rs[i].type;
        switch (type) {
            case "container":
                //20181207：这里PC和手机的分行与否判定还没做
                if (rs[i].value.showBool || active) {
                    let newDiv = $(`<div id="${rs[i].value.containerID}" class="${rs[i].value.class}"></div>`);
                    parent.append(newDiv);
                    if (rs[i].value.containerID != "") containerList[rs[i].value.containerID] = rs[i].value.items;
                    load(rs[i].value.items, newDiv);//迭代
                }
                break;
            case "title": {
                parent.append(`<h1>${rs[i].value.titleInput}</h1>`);
                break;
            }
            case "subtitle": {
                parent.append(`<h2>${rs[i].value.subTitleInput}</h2>`);
                break;
            }
            case "righttitle": {
                parent.append(`<div class="address">${rs[i].value.titleInput}</div>`);
                break;
            }
            case "img": {
                parent.append(`<img src="${rs[i].value.imgUrlInput}">`);
                break;
            }
            case "text": {
                parent.append(rs[i].value.textInput);
                break;
            }
            case "dimension": {
                //20181207：目前的方案是写json路径，通过数据类型的设定设置数据格式写入；也有对象编辑的雏形想法，但还不实际
                let num = 0;
                if (rs[i].value.dimensionNumType == "const") num = rs[i].value.dimensionJson;
                else eval(`num=numType(${rs[i].value.dimensionJson},"${rs[i].value.dimensionNumType}");`);
                parent.append(`
                                <div class="num-1">
                                    <div class="num">
                                        <h1 class="red-D">${num}</h1>
                                        <h2>${rs[i].value.dimensionName}</h2>
                                        <h3 data-type="json">${rs[i].value.dimensionIndex}</h3>
                                    </div>
                                </div>
                            `);
                break;
            }
            case "chart": {
                let chartCard;
                let chartDiv;
                var chartWidth = parent.width();
                if (rs[i].value.chartSize == "1:1") {
                    if (window.innerWidth <= window.innerHeight * 0.8) {
                        //手机纵向
                        chartCard = $(`
                                <div class="e-charts-card" style="width:${chartWidth}px;cursor: pointer;">
                                    <h1>${rs[i].value.chartTitle}</h1>
                                    <h2>点击全屏查看</h2>
                                </div>
                            `);
                        chartDiv = $(`<div class="chart" style="height: ${chartWidth}px;">Echarts</div>`);
                    }
                    else {
                        //PC横向
                        chartCard = $(`
                                <div class="e-charts-card" style="width:${0.43 * chartWidth}px;margin-left:${0.05 * chartWidth}px;cursor: pointer;">
                                    <h1>${rs[i].value.chartTitle}</h1>
                                    <h2>点击全屏查看</h2>
                                </div>
                            `);
                        chartDiv = $(`<div class="chart" style="height: ${0.43 * chartWidth}px;">Echarts</div>`);
                    }
                }
                else if (rs[i].value.chartSize == "2:1") {
                    chartCard = $(`
                                <div class="e-charts-card" style="width:${chartWidth}px;cursor: pointer;">
                                    <h1>${rs[i].value.chartTitle}</h1>
                                    <h2>点击全屏查看</h2>
                                </div>
                            `);
                    chartDiv = $('<div class="chart" style="height: 200px;">Echarts</div>');
                }

                chartList.push({
                    dom: chartDiv,
                    dome: rs[i].value.chartDemo,
                    size: rs[i].value.chartSize
                });
                chartCard.prepend(chartDiv);
                parent.append(chartCard);
                break;
            }
            case "table": {
                for (let j = 0; j < rs[i].value.tableCols[0].length; j++) {
                    rs[i].value.tableCols[0][j].edit = "";
                }
                //利用json的字符串序列化方法将指针变成对象
                let tableCols = JSON.parse(JSON.stringify(rs[i].value.tableCols));
                let tableData = JSON.parse(JSON.stringify(rs[i].value.tableData));
                //若检测到JSON格式的数据，则转换
                for (let j = 0; j < tableData.length; j++) {
                    for (let k = 0; k < tableCols[0].length; k++) {
                        tableData[j][tableCols[0][k].field] = JSONtest(tableData[j][tableCols[0][k].field]);
                    }
                }
                let itemTable = $('<div id="tableSet" class="layui-form-item"><table id="tableSetB" class="layui-hide" lay-filter="tableSetB"></table></div>');
                parent.append(itemTable);
                setTable();
                function setTable() {
                    layui.use('table', function () {
                        var table = layui.table;
                        //展示已知数据
                        table.render({
                            elem: '#tableSetB'
                            , cellMinWidth: 100
                            , cols: tableCols
                            , data: tableData
                            , even: true
                        });
                    });
                }
                break;
            }
            case "divd": {
                parent.append(`<div class="divd"><div class="divd-line"></div></div>`);
                break;
            }
            case "backBtn": {
                parent.append(`<div class="back" style="cursor: pointer;"><i class="iconfont icon-back"></i></div>`);
                break;
            }
            case "indexBtn": {
                let title = JSONtest(rs[i].value.titleInput);
                let btn = $(`
                    <div id="${rs[i].value.btnID}" class="${rs[i].value.class}" style="cursor: pointer;">
                        <i class="iconfont ${rs[i].value.icon}"></i>
                        <h1>${title}</h1>
                        <h2>${rs[i].value.subTitleInput}</h2>
                    </div>
                `);
                if (rs[i].value.indexID != "") {
                    btn.on("click", function () {
                        anaPart(rs[i].value.indexID, true, rs);
                    });
                }
                parent.append(btn);
                break;
            }
            case "productSwiper": {
                let swiperContainer = $(`<div class="swiper-container top-title-swiper" id="${rs[i].value.swiperID}">`);
                let swiperWrapper = $(`<div class="swiper-wrapper"></div>`);
                for (let j = 0; j < fe_rep._fe_rep_product.length; j++) {
                    swiperWrapper.append(`<div class="swiper-slide"><div data-swiper-parallax="0" data-swiper-parallax-opacity="0.5" class="top-title-element">${fe_rep._fe_rep_product[j].nv9}</div></div>`);
                }
                swiperContainer.append(swiperWrapper);
                parent.append(swiperContainer);
                YFID = fe_rep._fe_rep_product[0].nv1;
                let times = 0;
                new Swiper(`#${rs[i].value.swiperID}`, {
                    direction: 'horizontal', // 垂直切换选项
                    loop: false, // 循环模式选项
                    slidesPerView: 'auto',
                    centeredSlides: true,
                    spaceBetween: 10,
                    slideToClickedSlide: true,
                    parallax: true,
                    on: {
                        //slideChange: function () {
                        slideChangeTransitionEnd: function () {
                            //初始化就会触发一次这个事件，不知道为什么，而此时需要刷新的页面还未定义，所以才加了一个判断器times
                            if (times > 0) {
                                YFID = fe_rep._fe_rep_product[this.activeIndex].nv1;
                                containerRefresh(rs[i].value.refreshContainerID);
                            }
                            else times++;
                        },
                    },
                });
                break;
            }
            case "html": {
                parent.append(JSONtest(rs[i].value.htmlText));
                break;
            }
        }
    }
    for (let i = 0; i < chartList.length; i++) {
        anaChart(chartList[i].dom, chartList[i].dome, chartList[i].size);
    }
}
//容器重新加载，仅适用于因某个变量导致的局部刷新，如swiper
function containerRefresh(id) {
    layui.use('layer', function () {
        var layer = layui.layer;
        var loading = layer.load();
        var dom = $(`#${id}`);
        dom.empty();
        load(containerList[id], dom);
        layer.close(loading);
    });
}
//获取url参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return ""; //返回参数值
}
//相当于sql的where筛选器
function createIndexMap(rs, field) {
    var newRs = {};
    for (var i = 0; i < rs.length; i++) {
        if (!newRs[rs[i][field]]) newRs[rs[i][field]] = [];
        newRs[rs[i][field]].push(rs[i]);
    }
    return newRs;
}
//为oldmap(json)创建查询表，可以id为索引，直接attr查询表可生效
function createLookMap(oldmap, field) {
    var map = {};//创建一个空的json对象
    for (var i = 0; i < oldmap.length; i++) {
        var value = oldmap[i];//将数组中的元素作为json对象的值
        var key = value[field];//选取一个属性作为新的json对象的key
        map[key] = value;
    }
    return map;
}
//数据格式处理
function numType(num, type) {
    switch (type) {
        case "percent":
            return (parseFloat(num) * 100).toPrecision(3) + "%";
            break;
        case "money":
            return accounting.formatNumber(num);
            break;
        case "int":
            return Math.round(num);
            break;
        case "float":
            return parseFloat(num).toFixed(2);
            break;
        case "date1":
            let date = new Date(num);
            let y = date.getFullYear().toString();
            let m = date.getMonth() + 1;
            m = m < 10 ? ('0' + m) : m;
            let d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '.' + m + '.' + d;
            break;
        case "date2":
            let date2 = new Date(num);
            let y2 = date2.getFullYear().toString();
            y2 = y2.substr(2, 2);
            let m2 = date2.getMonth() + 1;
            m2 = m2 < 10 ? ('0' + m2) : m2;
            let d2 = date2.getDate();
            d2 = d2 < 10 ? ('0' + d2) : d2;
            return y2 + '.' + m2 + '.' + d2;
            break;
        case "text":
            return num;
        case "const":
            return num;
    }
}
//将文本中JSON部分数据替换为其数据后整理格式并返回；格式为{JSON:(object,type)}
function JSONtest(text) {
    if ($.isEmptyObject(text)) return ""
    var result = "";
    var param;//传入内容数组[json路径，数据转换格式]
    var regex1 = /{(.+?)}/g;//找出所有被大括号包围的部分
    var regex2 = /\((.+?)\)/g;//找出所有被小括号包围的部分
    var options1 = text.match(regex1);
    var options2;
    if (!$.isEmptyObject(options1)) {
        for (let i = 0; i < options1.length; i++) {
            //判断这部分字符串是否以"JSON:"开头
            if (options1[i].indexOf("JSON:") == 1) {
                options2 = options1[i].match(regex2);
                if (!$.isEmptyObject(options2)) {
                    param = options2[0].substring(1, options2[0].length - 1).split(',');
                    if (param.length == 1) param.push("const");
                    eval(`result=${param[0]};`);
                    result = numType(result, param[1]);
                    text = text.replace(options1[i], result);
                }
            }
        }
    }
    return text;
}
//截图
function captureComp() {
    $("#compAnaBtn").click();
    setTimeout(function () {
        html2canvas($(".body-inside")[1]).then(function (canvas) {
            var alink = document.createElement("a");
            alink.href = canvas.toDataURL();
            alink.download = "截图-time_" + Date.parse(new Date()) + ".png";
            alink.click();
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.msg("保存成功！");
                $($(".body-inside")[1]).find(".section-header").find(".back").click();
            });
        });
    }, 1000);
}